package com.slj.cloudaibaba.service.impl;

import com.slj.cloudaibaba.client.PayClient;
import com.slj.cloudaibaba.entity.OrderEntity;
import com.slj.cloudaibaba.model.response.PayDTO;
import com.slj.cloudaibaba.repository.OrderRepository;
import com.slj.cloudaibaba.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private PayClient payClient;

    @Override
    public String getPort() {
        String url = "http://cloud-alibaba-pay/pay/port";
        return restTemplate.getForObject(url, String.class);
    }

    @Override
    @GlobalTransactional(name = "create-order", rollbackFor = Exception.class)
    public void insert(OrderEntity orderEntity) {
        //xid检查
        String xid = RootContext.getXID();
        //1. 新建订单
        log.info("==================>开始新建订单" + "\t" + "xid_order:" + xid);
        OrderEntity order = orderRepository.save(orderEntity);
        PayDTO payDTO = new PayDTO();
        payDTO.setOrderId(order.getId());
        payDTO.setPrice(1);
        if ("albert".equals(orderEntity.getUserName())) {
            payDTO.setPrice(-1);
        }
        payClient.save(payDTO);
        log.info("==================>结束新建订单" + "\t" + "xid_order:" + xid);
    }

    @Override
    public List<OrderEntity> findAll() {
        return orderRepository.findAll();
    }
}
